import json

import requests

from utils.FileUtil import read_file_as_octet_stream


def getAccessToken(userConfig):
    url = "https://connect-api.cloud.huawei.com/api/oauth2/v1/token"
    
    headers = {
        "Content-Type": "application/json"
    }

    payload = {
        "grant_type" : "client_credentials",
        "client_id" : userConfig["client_id"],
        "client_secret": userConfig["client_secret"]
    }

    responses = requests.post(url, json=payload, headers=headers)

    if responses.status_code == 200:
        token_date = responses.json()
        print("获取accessToken成功:" + token_date["access_token"])
    else:
        print("获取accessToken失败")
    return

def getUploadUrlObs(userConfig, fileNameAppIdDict, fileSize):
    url = "https://connect-api.cloud.huawei.com/api/publish/v2/upload-url/for-obs"

    headers = {
        "Content-Type": "application/json",
        "client_id" : userConfig["client_id"],
        "Authorization" : "Bearer " + userConfig["access_token"]
    }

    payload = {
        "appId" : fileNameAppIdDict["app_id"],
        "fileName" : fileNameAppIdDict["file_name"],
        "contentLength" : fileSize
    }

    responses = requests.get(url, params=payload, headers=headers)
    result = responses.json()

    print("=== 获取上传API 响应 ===")
    print(json.dumps(result, indent=2, ensure_ascii=False))

    return result.get("urlInfo")


def uploadAppBaseInfo(userConfig, appInfo):
    url = "https://connect-api.cloud.huawei.com/api/publish/v3/app-info"

    headers = {
        "Content-Type": "application/json",
        "client_id": userConfig["client_id"],
        "Authorization": "Bearer " + userConfig["access_token"]
    }

    query = {
        "appId" : appInfo.app_id
    }

    payload = {
        "publishCountry" : "CN",
        "encrypted" : 0,
        "harmonyChildType" : 20000002,
        "kindMainTag" : 25000003,
        "kindSubTags" : [25000004, 25000005],
        "registeredDclType" : 2,
        "publicationNumber" : "免责函",

    }

    responses = requests.put(url, params=query, json=payload, headers=headers)

    print("=== 更新文件基本信息API 响应===")
    print(responses.json())

def appLanguageInfo(userConfig, appInfo):
    url = "https://connect-api.cloud.huawei.com/api/publish/v3/app-language-info"
    headers = {
        "Content-Type": "application/json",
        "client_id": userConfig["client_id"],
        "Authorization": "Bearer " + userConfig["access_token"]
    }

    query = {
        "appId": appInfo.app_id
    }

    payload = {
        "lang" : "zh-CN",
        "appDesc" : "this is a appDesc",
        "briefInfo" : "this is a briefInfo",
        "privacyPolicy": appInfo.privacy_policy_url
    }

    responses = requests.put(url, params=query, json=payload, headers=headers)

    print("=== 更新文件语言信息API 响应===")
    print(responses.json())

def uploadFile(urlInfo, fileContent):
    responses = requests.put(urlInfo["url"], data=fileContent, headers=urlInfo["headers"])

    print("=== 上传文件API 响应===")
    print(responses)

def updateAppFileInfo(userConfig, appInfo):
    url = "https://connect-api.cloud.huawei.com/api/publish/v3/app-file-info"
    headers = {
        "Content-Type": "application/json",
        "client_id": userConfig["client_id"],
        "Authorization": "Bearer " + userConfig["access_token"]
    }

    query = {
        "appId": appInfo.app_id
    }

    fileInfos = read_file_as_octet_stream(appInfo)
    objectDict = {}
    screenshotList = []
    iconList = []
    publicationList = []

    # 依次上传screenshot信息
    for index in range(len(fileInfos["screenshotList"]["screenshotSize"])):
        fileName = fileInfos["screenshotList"]["screenshotName"][index]
        fileNameAppIdDict = {"file_name" : fileName, "app_id": appInfo.app_id}
        urlInfo = getUploadUrlObs(userConfig, fileNameAppIdDict, fileInfos["screenshotList"]["screenshotSize"][index])
        screenshotList.append(urlInfo["objectId"])
        uploadFile(urlInfo, fileInfos["screenshotList"]["screenshotContent"][index])

    # 上传icon信息和publication信息
    for uploadName in ["icon", "publication"]:
        fileName = fileInfos[uploadName + "Dict"][uploadName + "Name"]
        fileNameAppIdDict = {"file_name" : fileName, "app_id": appInfo.app_id}
        urlInfo = getUploadUrlObs(userConfig, fileNameAppIdDict, fileInfos[uploadName + "Dict"][uploadName + "Size"])
        if uploadName == "icon":
            iconList.append(urlInfo["objectId"])
        elif uploadName == "publication":
            publicationList.append(urlInfo["objectId"])
        uploadFile(urlInfo, fileInfos[uploadName + "Dict"][uploadName + "Content"])


    objectDict["screenShotList"] = screenshotList
    objectDict["appIconList"] = iconList
    objectDict["publicationList"] = publicationList
    payload = {
        "appIconList": [{
          "lang": "zh-CN",
          "fileInfoList": [{
            "deviceType": 4,
            "objectIdList": objectDict["appIconList"],
            "showType": 0
          }]
        }
      ],
      "screenShotList": [{
        "lang": "zh-CN",
        "fileInfoList": [{
          "deviceType": 4,
          "objectIdList": ["CN/20241118**/17319******.png",
          "CN/20241118**/17319******.png"],
          "showType": 0
        },
        # {
        #   "deviceType": 5,
        #   "objectIdList": ["CN/20241118**/17319******.png"],
        #   "showType": 0
        # }
        ]
      }],
      # "elecCertificate": objectDict["elecCertificate"],
      # "certificateList": objectDict["certificateList"],
      "publicationList": objectDict["publicationList"],
    }

    responses = requests.put(url, json=payload, params=query, headers=headers)
    print("===更新文件信息API响应===")
    print(responses.text)

